﻿using Prism.DryIoc;
using Prism.Ioc;
using System;
using System.Threading;
using System.Windows;
using TiaoTiaoCode.AutoUpdate.ServerUI.DialogWindows;
using TiaoTiaoCode.AutoUpdate.ServerUI.MainFrame;
using TiaoTiaoCode.AutoUpdate.ServerUI.Splashs;
using TiaoTiaoCode.AutoUpdate.ServerUI.ViewModels;
using TiaoTiaoCode.AutoUpdate.ServerUI.Views;

namespace TiaoTiaoCode.AutoUpdate.ServerUI
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : PrismApplication
    {
        protected override Window CreateShell()
        {
            return Container.Resolve<MainView>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterSingleton<SplashManager>();

            containerRegistry.RegisterForNavigation<MainProgramManagerView, MainProgramManagerViewModel>();
            containerRegistry.RegisterForNavigation<MainProgramPublishView, MainProgramPublishViewModel>();

            containerRegistry.RegisterDialogWindow<MyDialogWindow>("NormalDialogWindow");

            containerRegistry.RegisterDialog<MainProgramCreateView, MainProgramCreateViewModel>(nameof(MainProgramCreateView));
            containerRegistry.RegisterDialog<UploadPublishZipView, UploadPublishZipViewModel>(nameof(UploadPublishZipView));

            // loading
            containerRegistry.RegisterDialog<LoadingDialog, LoadingDialogViewModel>("LoadingWindow");
        }

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        static Mutex? _mutex;

        protected override void OnStartup(StartupEventArgs e)
        {
            bool createNew;
            _mutex = new Mutex(true, "TiaoTiaoUpgrade", out createNew);
            if (createNew)
                base.OnStartup(e);
            else
                Shutdown();
        }

        private void PrismApplication_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true;

            if (e.Exception is DivideByZeroException dex)
                MessageBox.Show($"发生异常，但可继续运行\r\n{dex.Message}");
            else
                MessageBox.Show($"程序异常：{e.Exception.Message}");
        }
    }
}
